import os,sys
sys.path.append(os.path.dirname(sys.path[0]))
from fastapi import APIRouter,status,HTTPException,Request,Query,Depends
from db.db_operate import kinetica
from models.collections import create_collections
from models.items import Createitems
import json
from typing import List, Optional,Union

items_api = APIRouter()


def bbox_query(bbox: Optional[List[Union[float, int]]] = Query(None)):
    return bbox

@items_api.get("/collections/{collection_id}/items")
def get_items(request:Request,collection_id:str,limit:int=10,bbox=Depends(bbox_query),datetime:str=None,token:str=None):
   
    try:
        host = request.url.hostname
        port = request.url.port
        sqls,tokenstatus,offsetco,count=kinetica.get_sql(collection_id,limit,bbox,datetime,token)
        response=kinetica.get_items(sqls)
       
        itms=Createitems(response,host,port,collection_id,limit,tokenstatus,offsetco,count).create_items()
       
        return itms
    except:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
        


@items_api.get("/collections/{collection_id}/items/{item_id}")
def get_itemid(request:Request,collection_id:str,item_id:str):
    
    try:
        host = request.url.hostname
        port = request.url.port
        response=kinetica.get_itemid(collection_id,item_id)
        itms=Createitems(response,host,port,collection_id,1,1).create_itemid()
       
        return itms
    except:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
        

@items_api.get("/collections/{collection_id}/datetime")
def get_itemid(collection_id:str):
    
    try:
        response=kinetica.get_itemDatetime(collection_id)
        
        datetime=json.loads(response["json_encoded_response"])
        
        return {"collection":f"{collection_id}","maxdatetime":datetime["column_1"][0],"mindatetime":datetime["column_2"][0]}
    except:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
